import React, {Component} from 'react';
import {Button, Input, Table, Form, Row, Col, Select, Modal, Pagination} from 'antd';
import {EditLogistics} from "../components/EditComponent";
import {ButtonSubmit} from "../components/AddComponent";
import {logistics} from '../value';
import app from '../AppMethod';
import {Consumer} from "../store";
import MapComponent from '../components/MapComponent';

const FormItem = Form.Item;
const Option = Select.Option;
const confirm = Modal.confirm;

class Logistic extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            pagination: {
                current: 0,
                total: 0,
                pageSize: 0
            },
            allPage: 0,
            searchData: {},
            data: [],
            locationData: {
                address: '广东省, 佛山市, 南海区, 佛平二路, 88号',
                latitude: '23.036742',//纬度
                longitude: '113.149856'//经度
            },
            logistics_id: '',
            logistics_name: '',
            logistics_phone: '',
            editVisible: false,
            editType: 0
        }
    };

    columns = [
        {
            title: '物流公司',
            dataIndex: 'logistics_name',
        },
        {
            title: '地址',
            dataIndex: 'logistics_address'
        },
        {
            title: '电话',
            dataIndex: 'logistics_phone'
        },
        {
            title: '经纬度',
            dataIndex: 'logistics_x_y'
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (
                    <span>
                    <span style={{color: '#1890ff', cursor: 'pointer'}}
                          onClick={() => this.setModal2Visible(true, 2, data)}>修改</span>
                    <span style={{marginLeft: '10px', color: '#f5222d', cursor: 'pointer'}}
                          onClick={() => this.handleDelete(data.logistics_id)}>删除</span>
                    </span>
                )
            }
        }
    ];
    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };

    render() {
        return (
            <div>
                <Row>
                    <SearchLists
                        clickSearch={(value) => {
                            this.handleGetSearch(value)
                        }}
                    >
                    </SearchLists>
                </Row>
                <Row>
                    <Button type="primary" onClick={() => this.setModal2Visible(true, 1, {})}>添加</Button>
                </Row>
                <Row style={{marginTop: '20px'}}>
                    <Col span={24}>
                        <Table
                            columns={this.columns}
                            rowKey={record => record.logistics_id}
                            dataSource={this.state.data}
                            pagination={false}
                            loading={this.state.loading}
                        />
                    </Col>
                </Row>
                <Row style={{marginTop: '20px'}}>
                    <Col span={12} style={{fontSize: '15px'}}>
                        共 {this.state.pagination.total} 条记录 第 {this.state.pagination.current} / {this.state.allPage}
                        页
                    </Col>
                    <Col span={12} style={{textAlign: 'right'}}>
                        <Pagination {...this.state.pagination} showSizeChanger={true} showQuickJumper={true}
                                    onChange={(page, pageSize) => this.handlePageChange(page, pageSize)}
                                    onShowSizeChange={(current, size) => this.handleSizeChange(current, size)}
                                    hideOnSinglePage={false}/>
                    </Col>
                </Row>
                <div>
                    <Modal
                        maskClosable={true}
                        confirmLoading={this.state.editConfirmLoading}
                        title={'请输入'}
                        wrapClassName="vertical-center-modal"
                        width={'1000px'}
                        visible={this.state.editVisible}
                        onCancel={() => this.setModal2Visible(false)}
                        footer={[
                            <Button key="back" type="default" onClick={() => this.setModal2Visible(false)}>取消</Button>,
                            <Button key="submit" type='primary' onClick={() => this.handleSubmit()}>确定</Button>
                        ]}
                    >
                        <Row>
                            <Col offset={1} span={22}>
                                <Row style={{marginTop: '15px'}}>
                                    <Col span={2} style={{height: '32px', lineHeight: '32px'}}>物流公司：</Col>
                                    <Col span={5}><Input value={this.state.logistics_name} placeholder="请输入"
                                                         onChange={(e) => this.handleNameChange(e)}/></Col>
                                </Row>
                                <Row style={{marginTop: '15px'}}>
                                    <Col span={2} style={{height: '32px', lineHeight: '32px'}}>电话：</Col>
                                    <Col span={5}><Input value={this.state.logistics_phone} placeholder="请输入"
                                                         onChange={(e) => this.handlePhoneChange(e)}/></Col>
                                </Row>
                                <Row style={{marginTop: '20px'}}>
                                    <MapComponent getPoint={(values) => this.getPoint(values)}
                                                  locationData={this.state.locationData}/>
                                </Row>
                                <Row style={{marginTop: '20px'}}>
                                    <Col span={24}>地址：{this.state.locationData.address}</Col>
                                </Row>
                                <Row style={{marginTop: '15px'}}>
                                    <Col span={7}>经度：{this.state.locationData.longitude}</Col>
                                    <Col span={7}>纬度：{this.state.locationData.latitude}</Col>
                                </Row>
                            </Col>
                        </Row>
                    </Modal>
                </div>
            </div>
        )
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({menuType: "物流管理"});
        this.handleSearchLogistics();
    };

    componentWillUnmount() {
        this.setState = (count, callback) => {
            return;
        }
    };

    /**
     * 处理物流公司名变化事件
     */
    handleNameChange(e) {
        this.setState({logistics_name: e.target.value});
    };

    /**
     * 处理物流公司电话变化事件
     */
    handlePhoneChange(e) {
        this.setState({logistics_phone: e.target.value});
    };

    /**
     * 显示和隐藏添加弹框
     * @param visible
     */
    handleCancel(visible) {
        this.setState({isAddValid: visible});
    };

    /**
     * 查询物流公司列表
     * @param data
     */
    handleSearchLogistics(data = {page: 1, size: 10}) {
        this.setState({loading: true});
        app.post(logistics.SEARCH_LOGISTICSLIST, data).then((result) => {
            if (result.code === 1) {
                let count = result.data.count;
                let pagination = {
                    current: data.page,
                    pageSize: data.size,
                    total: count
                };
                let allPage;
                if (count % data.size > 0) {
                    allPage = parseInt(count / data.size) + 1;
                } else {
                    allPage = count / data.size;
                }
                let dataSet = result.data.dataSet;
                for (let i = 0; i < dataSet.length; i++) {
                    dataSet[i].logistics_x_y = dataSet[i].logistics_x + ' , ' + dataSet[i].logistics_y;
                }
                this.setState({pagination, data: result.data.dataSet, loading: false, allPage});
            } else {
                let pagination = {
                    current: 0,
                    pageSize: 0,
                    total: 0
                };
                let allPage = 0;
                this.setState({data: [], loading: false, pagination, allPage});
            }
        })
    };

    /**
     * 处理分页跳转事件
     * @param page
     * @param size
     */
    handlePageChange(page, size) {
        let data = this.state.searchData;
        data.page = page;
        data.size = size;
        this.handleSearchLogistics(data);
    };

    /**
     * 处理页数变化事件
     * @param current
     * @param size
     */
    handleSizeChange(current, size) {
        let data = this.state.searchData;
        data.page = current;
        data.size = size;
        this.handleSearchLogistics(data);
    };

    /**
     * 根据条件查找物流公司列表
     * @param value
     */
    handleGetSearch(value) {
        this.setState({searchData: value});
        let data = {
            page: 1,
            size: this.state.pagination.pageSize || 10,
            logistics_name: value.logistics_name
        };
        console.log(data);
        this.handleSearchLogistics(data);
    };

    /**
     * 处理添加物流公司事件
     */
    handleSubmit() {
        let _this = this;
        let url='';
        let data = {};
        let editType = this.state.editType;
        if (editType == 1) {
            data = {
                logistics_name: this.state.logistics_name,
                logistics_phone: this.state.logistics_phone,
                logistics_address: this.state.locationData.address,
                logistics_x: this.state.locationData.longitude,
                logistics_y: this.state.locationData.latitude,
            };
            url=logistics.ADD_LOGISTICS;
        } else if (editType == 2) {
            data = {
                logistics_id:this.state.logistics_id,
                logistics_name: this.state.logistics_name,
                logistics_phone: this.state.logistics_phone,
                logistics_address: this.state.locationData.address,
                logistics_x: this.state.locationData.longitude,
                logistics_y: this.state.locationData.latitude,
            };
            url=logistics.UPDATE_LOGISTICS;
        }
        app.post(url, data).then((result) => {
            if (result.code === 1) {
                    app.alert(result.msg, 'success', 3);
                this.setState({
                    logistics_id: '',
                    logistics_name:'',
                    logistics_phone:'',
                    editVisible: false,
                    editType: 0
                });
                _this.handleSearchLogistics();
            } else {
                    app.alert(result.error, 'error', 3);

            }
        })
    };

    /**
     * 处理删除物流公司事件
     * @param id
     */
    handleDelete(id) {
        let _this = this;
        confirm({
            title: '',
            content: '您确认删除这条数据吗？',
            onOk() {
                app.post(logistics.DEL_LOGISTICS, {logistics_id: id}).then((result) => {
                    if (result.code === 1) {
                        app.alert('删除成功', 'success', 3);
                        _this.handleAfterDel();
                    } else {
                        app.alert('删除失败', 'error', 3);
                    }
                })
            },
            onCancel() {
            },
        })
    };

    /**
     * 处理编辑事件
     */
    handleEdit() {
        let data = this.state.searchData;
        data.page = this.state.pagination.current ? this.state.pagination.current : 1;
        data.size = this.state.pagination.pageSize ? this.state.pagination.pageSize : 10;
        this.handleSearchLogistics(data);
    };

    /**
     * 处理删除后查询物流公司列表功能
     */
    handleAfterDel() {
        let data = this.state.searchData;
        data.page = 1;
        data.size = 10;
        this.handleSearchLogistics(data);
    };

    /**
     * 获取地址和经纬度事件
     * @param values
     */
    getPoint(values) {
        this.setState({
            locationData: values
        })
    };

    /**
     * 处理修改物流公司弹框事件
     * @param visible
     * @param data
     */
    setModal2Visible(visible, type, data) {
        if (visible && type == 2) {
            let locationData = {
                address: data.logistics_address,
                latitude: data.logistics_y,//纬度
                longitude: data.logistics_x//经度
            };
            this.setState({
                logistics_id: data.logistics_id,
                logistics_name:data.logistics_name,
                logistics_phone:data.logistics_phone,
                locationData,
            })
        }
        this.setState({editVisible: visible, editType: type});
    };
};

class SearchList extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    };

    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <div>
                <Row>
                    <Form className="login-form">
                        <Row>
                            <Col span={8}>
                                <FormItem label="物流公司" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('logistics_name')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col offset={10} span={6} style={{float: 'right'}}>
                                <Button type="primary"
                                        onClick={() => this.handleSearchComplain()}
                                >
                                    查询
                                </Button>
                                <Button type="default"
                                        onClick={() => this.handleReset()}
                                        style={{marginLeft: '10px'}}
                                >
                                    重置
                                </Button>
                            </Col>
                        </Row>
                    </Form>
                </Row>
            </div>
        )
    };

    componentDidMount() {

    };

    /**
     * 获取搜索条件
     */
    handleSearchComplain() {
        this.props.form.validateFields((err, values) => {
            this.props.clickSearch(values);
        })
    };

    /**
     * 处理重置按钮事件
     */
    handleReset() {
        this.props.form.resetFields();
        this.props.clickSearch({logistics_name: null});
    };

    /**
     * 处理输入框按下回车键的事件
     */
    handleOnPressEnter() {
        //调用获取搜索条件的函数
        this.handleSearchComplain();
    };
};

const SearchLists = Form.create()(SearchList);
const Logistics = Form.create()(Logistic);
export default prop => (
    <Consumer>
        {
            props => (
                <Logistics {...prop} {...props}/>
            )
        }
    </Consumer>
);